<?php

class IteracionController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

        /**
        * @var private property containing the associated Project model
        instance.
        */
        private $_experimento = null;
                    
        
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
                        'experimentoContext + create index admin', //check to ensure valid experimento context
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'addEV'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Iteracion;
                $model->idExperimento = $this->_experimento->id;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Iteracion']))
		{
			$model->attributes=$_POST['Iteracion'];
                        $model->datos=CUploadedFile::getInstance($model,'datos');
                        
                        if($model->save())
                        {
				$path = realpath(Yii::app()->basePath . '/../images');
                                $model->datos->saveAs($path.'/'.$model->datos);
                                $this->saveXML($model->datos, $model->id);
                                $this->redirect(array('view','id'=>$model->id));
                        }
		}

		$this->render('create',array('model'=>$model,));
                
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Iteracion']))
		{
			$model->attributes=$_POST['Iteracion'];
			
                        if($model->fechaFin > $model->fechaIni)
                        {
                            if($model->save())
				$this->redirect(array('view','id'=>$model->id));
                        }
                        else
                        {
                            Yii::app()->user->setFlash('error',"The end dat must be after the start date" );
                        }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Iteracion'
                , array(
                'criteria'=>array(
                'condition'=>'idExperimento=:experimentoId',
                'params'=>array(':experimentoId'=>$this->_experimento->id),
                ),
                ));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Iteracion('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Iteracion']))
			$model->attributes=$_GET['Iteracion'];
		
                 $model->idExperimento = $this->_experimento->id;
                
                $this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Iteracion the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Iteracion::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Iteracion $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='iteracion-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
         /** Protected method to load the associated Experimento model class
        * @param integer experimentoId the primary identifier of the
        associated Experimento
        * @return object the Experimento data model based on the primary key
        */
        protected function loadExperimento($experimentoId) 
        {
            //if the experimento property is null, create it based on input id
            if($this->_experimento===null)
            {
                $this->_experimento= Experimento::model()->findByPk($experimentoId);
                if($this->_experimento===null)
                {
                    throw new CHttpException(404,'The requested experimento does not exist.');
                }
            }
            return $this->_experimento;
        }
        
        
        /**
        * In-class defined filter method, configured for use in the above filters()
            * method. It is called before the actionCreate() action method is run in
            * order to ensure a proper project context
        */
        public function filterExperimentoContext($filterChain) 
        {
            //set the project identifier based on GET input request variables
            if (isset($_GET['pid']))
                $this->loadExperimento($_GET['pid']);

            else
                throw new CHttpException(403, 'Must specify a experimento before performing this action.');
            //complete the running of other filters and execute the requested action            
            $filterChain->run();
        }
        
        
        /**
        * Provides a form so that project administrators can
        * associate other users to the project
        */
        public function actionAddEV($id)
        {
            $iteracion = $this->loadModel($id);
            
            /*if(!Yii::app()->user->checkAccess('createUsuario', array('proyecto'=>$project)))
            {
                throw new CHttpException(403,'You are not authorized to perform this action.');
            }*/
            $form=new VariableIteracionForm;
            // collect user input data
            if(isset($_POST['VariableIteracionForm']))
            {
                $form->attributes=$_POST['VariableIteracionForm'];
                $form->iteracion = $iteracion;
             
                // validate user input
                if($form->validate())
                {
                    if($form->assign())
                    {
                        Yii::app()->user->setFlash('success'," The equipo and variable has been added to the project." );
                        //reset the form for another user to be associated if desired
                        $form->unsetAttributes();
                        $form->clearErrors();
                    }
                }
             }
             $form->iteracion = $iteracion;
             $this->render('addEV',array('model'=>$form));
        }
        
        public function assignValor($equipoId, $variableId, $valor, $id)
        {
            $command = Yii::app()->db->createCommand();
            $command->insert('variablexiteracion', array(
                        'idVariable'=>$variableId,
                        'idEquipo'=>$equipoId,
                        'idIteracion'=>$id,
                        'valor'=>$valor,)
            );
        }
        
        
        public function saveXML($name, $id)
        {
            $path = realpath(Yii::app()->basePath . '/../images');
            $xml = simplexml_load_file($path.'/'.$name);
            
            $equipo;
            $variable;
            foreach($xml->children() as $child)
            {
                if($child->getName()=="equipo")
                {
                    $equipo= Equipo::model()->findByAttributes(array('nombre'=>$child));
                }
                if($child->getName()=="variable")
                {    
                      $variable=  Variable::model()->findByAttributes(array('nombre'=>$child));
                }
                if($child->getName()=="valor")
                {    
                      $this->assignValor($equipo->id, $variable->id, $child, $id);
                }
            }
            
        }
}
